<?php
/**
 * RadioMorningModel.class.php
 * 晨间电台控制器
 * 
 * @author 	王中艺	<wangzy_smile@qq.com>
 * @date 	2017-05-04
 */

namespace Wechat\Model;

class RadioMorningModel extends \Common\Model\RadioMorningModel {

	protected $cache 	= true;

	/**
	 * 获取最新电台
	 * @return 	$radioInfo
	 */
	public function getNewItem(){
		$radioInfo 	= $this->where('status != -1')->order('id desc')->cache(true)->find();
		$radioInfo 	= $this->_analyField('radio', $radioInfo);

		return $radioInfo;
	}

	/**
	 * 根据用户ID获取当前试听电台
	 * @param 	$userId
	 * @return 	$info
	 */
	public function getFreeItem($userId){
		$Redis 	= \Common\Util\Redis::getInstance();
		$playListKey 	= 'morning_radio_free_list_'.$userId;
		$date 	= date('Y-m-d');
		$info 	= $Redis->hGet($playListKey, $date);
		if(!$info){
			//清空Redis播放列表数据
			$Redis->del($playListKey);
			//将播放条目写入redis
			$playList 	= $this->getList(['is_try' => 1, 'status' => 1]);
			$_playList 	= [];
			$_index 	= 0;
			foreach($playList as $item){
				$_date 	= date('Y-m-d', strtotime('+'.$_index.' days'));
				$_playList[$_date]	= serialize($item);
				$_index++;
			}
			$Redis->hMset($playListKey, $_playList);
			$info 	= $_playList[$date];
		}

		return unserialize($info);
	}

	/**
	 * 获取排行榜
	 * @param 	$count 	排行数目
	 * @param 	&$userLisInfo 	我的排名 userId
	 * @return 	$list 	排行
	 */
	public function getRankList($count, &$userLisInfo = false){
		$list 	= M('t_radio_morning_log a', null)
			->join('left join t_user b on a.user_id = b.id')
			->order('a.count desc, a.user_id')
			->limit($count)
			->cache(true)
			->field('a.user_id, a.count, b.nickname, b.headimgurl, open_id')
			->select();

		if(is_numeric($userLisInfo)){
			$userId 	= $userLisInfo;
			$userLisInfo 	= S('user_radio_morning_lisinfo_'.$userId);
			if(!$userLisInfo){
				$userLisInfo 	= M('t_radio_morning_log', null)
					->where('user_id = %d', $userId)
					->find();

				$userLisCount 	= $userLisInfo['count'] ? $userLisInfo['count'] : 0;

				$count 	= M('t_radio_morning_log', null)
					->where('count > %d or (count = %d and user_id > %d)', $userLisCount, $userLisCount, $userId)
					->count();

				$userLisInfo['rank'] 	= $count + 1;

				//写入缓存
				S('user_radio_morning_lisinfo_'.$userId, $userLisInfo);
			}
		}

		return $list;
	}

	/**
	 * 记录动作
	 * @param 	$radioId	电台ID
	 * @param 	$userId 	用户ID
	 * @param 	$actionId 	动作标志
	 * @return 	boolean
	 */
	function logAction($radioId, $userId, $actionId = 3){
		//排行表写入
		$logInfo 	= M('t_radio_morning_log', null)->where('user_id = %d', $userId)->find();
		if(!$logInfo){
			$logInfo 	= ['user_id' => $userId, 'count' => 1];
			$result 	= M('t_radio_morning_log')->add($logInfo);
		}else{
			$logInfo['count']++;
			$result 	= M('t_radio_morning_log')->save($logInfo);
		}
		if($result === false){
			$this->errMsg 	= '播放动作记录失败!';
			return false;
		}

		return true;
	}
}